package cn.gogoyc.system.service.impl;

import cn.gogoyc.system.domain.Role;
import cn.gogoyc.system.mapper.RoleMapper;
import cn.gogoyc.system.service.IRoleService;
import cn.gogoyc.org.basic.servie.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Consumer;

/**
 * 角色业务实现类
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void save(Role role) {
        super.save(role);

        //添加角色时,如果他的菜单有值则
        if (role.getMenus()!=null && role.getMenus().size()>0) {
            //循环添加集合里面的数据
            roleMapper.addRoleMenus(role.getId(),role.getMenus());
        }
        //添加角色时,如果他的权限集合有值则
        if (role.getPermissions()!=null && role.getPermissions().size()>0) {
            //循环添加集合里面的数据
            roleMapper.addRolePermissions(role.getId(),role.getPermissions());
        }
    }

    @Override
    @Transactional
    public void remove(Long id) {
        roleMapper.removeMenusByRoleId(id);
        roleMapper.removePermissionsByRoleId(id);
        roleMapper.removeEmployeeRoleByRoleId(id);
        super.remove(id);
    }

    @Override
    @Transactional
    public void update(Role role) {
        //先删再修改,不然权限和菜单数据库数据会冗余,以防冲突
        roleMapper.removeMenusByRoleId(role.getId());
        roleMapper.removePermissionsByRoleId(role.getId());
        if (role.getMenus()!=null && role.getMenus().size()>0) {
            roleMapper.addRoleMenus(role.getId(),role.getMenus());
        }
        if (role.getPermissions()!=null && role.getPermissions().size()>0) {
            roleMapper.addRolePermissions(role.getId(),role.getPermissions());
        }
        super.update(role);
    }

    @Override
    @Transactional
    public void patchDelete(List<Long> ids) {
        //调用自有方法,循环删除
        ids.forEach(aLong -> remove(aLong));
    }
}
